package com.haredot.security;

import com.haredot.vo.R;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败的业务
 */
public class HaredotAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String message = exception.getMessage() ;

        // 如果是该异常、那么 提示用户名或密码不正确
        if (exception instanceof InternalAuthenticationServiceException || exception instanceof BadCredentialsException e) {
             message = "用户名或密码不正确" ;
        }else if (exception instanceof LockedException e) {
            message = "账户被锁定" ;
        }else if (exception instanceof DisabledException) {
            message = "账户被禁用";
        }

        R<?> result = R.fail(R.StatusCode.FAIL, message).build();

        new MappingJackson2HttpMessageConverter()
                .write(result, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
    }
}
